package cn.com.callback

import groovy.json.*;
import java.util.Map;

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

import java.text.ParseException
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import cn.com.elite.EliteBean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;

import cn.com.elite.Util;
import cn.com.kh.getProperty;
import cn.com.kh.KHUtil;


/**
 *
 * @Title: api_SzwgSSO
 * @Description: SSO人员定时同步
 * @author: Chieh
 * @date 2020-05-18 20:43:00
 *
 */

public class api_SzwgSSO implements ServiceBackInvoke{
	private static final Log log = LogFactory.getLog(api_SzwgSSO.class);
	public String doCallBack(EliteBean eliteBean,HttpServletRequest request,HttpServletResponse response) {
		
		
				String inURL = "";
				String inData = "";
				String outData = "";
		
				String tokenId;
				String pullTaskjson;
				String Finishreslut;
				String loginoutreslut;
				try {
					log.debug("getlogin开始获取tokenId数据...");
		
					tokenId = getlogin(eliteBean);
					//log.debug("getlogin结果"+tokenId);
		
					//设置开关pulltask和pullfinish两个接口配合起来完成一条数据的下拉。如果有多条数据，应该多次调用第2和第3两个接口，直到数据完全下拉完成。调用顺序 {1-->....2-->3-->2-->3-->2-->3 .....-->4}
					boolean onofftype =true;
					int i = 0;
					while(onofftype && i < 10000){
						i++;
						try {
		
							//log.debug("下拉任务 pullTask开始...");
							pullTaskjson=getpullTask(eliteBean,tokenId);
							//log.debug("下拉任务结果"+pullTaskjson);
							if(pullTaskjson == null || pullTaskjson.equals("null") || pullTaskjson.length() <= 0){
								onofftype=false;
								break;
							}
		
							JSONObject pullTaskjsonObject = new JSONObject(pullTaskjson);
							//log.debug("下拉pullTaskjsonObject:"+pullTaskjsonObject);
		
							String taskId = KHUtil.GetJV(pullTaskjsonObject, "taskId");
							String pullTasksuccess = KHUtil.GetJV(pullTaskjsonObject, "success");
							//String guid = KHUtil.GetJV(pullTaskjsonObject, "id");
							String data = KHUtil.GetJV(pullTaskjsonObject, "data");
		
							//log.debug("下拉data:"+data);
							JSONObject userdata = new JSONObject(data);
							String username = KHUtil.GetJV(userdata, "username");
		
							//log.debug("下拉完成 pullFinish开始："+taskId+"	pullTasksuccess："+pullTasksuccess+"	guid："+username);
							Finishreslut=getpullFinish(eliteBean,tokenId,taskId,pullTasksuccess,username);
							//log.debug("下拉完成结果"+Finishreslut);
		
							log.debug("次数:"+i);
						} catch (Exception e) {
							onofftype=false;
							log.debug("异常次数:"+i);
						}
					}
		
					
		
				} catch(Exception e) {
					log.error("处理异常" + e.getMessage());
					//失败返回
					outData = "处理异常" + e.getMessage();
				}finally{
					//log.debug("loginout开始...");
					loginoutreslut=getloginout(eliteBean);
					log.debug("loginout结果"+loginoutreslut);
					outData=loginoutreslut;
					log.debug(outData);
				}
				
			}
		
			// SSO 登陆获取tokenId
			public String getlogin(EliteBean eliteBean){
		
				//清理历史token
				getloginout(eliteBean);
		
				// 获取当前同步时间同步时间
				String timestamp = String.valueOf(System.currentTimeMillis());
				timestamp = timestamp.substring(0, 13);
		
				def url= getProperty.get("SSO.URL");
		
				// 设置头文件
				Map<String, String> headMap = new HashMap<String, String>();
				headMap.put("Content-Type", "application/x-www-form-urlencoded");
		
				try {
					JSONObject reqjson = new JSONObject();
					String callJson = "";
					reqjson.put("systemCode", getProperty.get("SSO.systemCode"));
					reqjson.put("integrationKey", getProperty.get("SSO.integrationKey"));
					reqjson.put("force", getProperty.get("SSO.force"));
					reqjson.put("timestamp", timestamp);
		
					callJson="method=login&request=" + reqjson.toString();
					log.debug("参数：" + callJson);
		
					String reJson = Util.doHttpPostUseHead(url, callJson, "UTF-8", 10000, 0, headMap);
		
					log.debug("调用结果返回：" + reJson.toString());
		
					String tokenId = null;
					if(reJson!=null&&reJson.length()>0) {
		
						try {
							JSONObject loginObject = new JSONObject(reJson);
							String success = KHUtil.GetJV(loginObject, "success");
							tokenId = KHUtil.GetJV(loginObject, "tokenId");
							log.debug("success:"+success+"	,tokenId："+tokenId);
							eliteBean.update("update SYSC_PARAMETER set PARAMETERVALUE = '"+tokenId+"' where PARAMETER_ID = 'SSOTOK'", "dataSource");
						} catch (Exception e) {
							tokenId = null;
						}
					}else {
		
					}
					return tokenId;
				} catch (Exception e) {
					log.error( "SSO 登陆获取tokenId处理失败，" + e.getMessage());
				}
			}
			// SSO 登出注销
			public String getloginout(EliteBean eliteBean){
		
				//查询历史Token
				def getSelectSQL = eliteBean.chaxun_sql("select PARAMETERVALUE from SYSC_PARAMETER where PARAMETER_ID = 'SSOTOK'",  "dataSource");
				log.debug("查询当前记录的Token SQL:" + getSelectSQL + " 结果数量:" + getSelectSQL.size());
		
				if(getSelectSQL.size() > 0) {
					String tokenId = getSelectSQL.get(0).get("PARAMETERVALUE");
					if(tokenId!=null&&tokenId.length()>0) {
		
						// 获取当前同步时间同步时间
						String timestamp = String.valueOf(System.currentTimeMillis());
						timestamp = timestamp.substring(0, 13);
						def url= getProperty.get("SSO.URL");
		
						// 设置头文件
						Map<String, String> headMap = new HashMap<String, String>();
						headMap.put("Content-Type", "application/x-www-form-urlencoded");
		
						try {
							JSONObject reqjson = new JSONObject();
							String callJson = "";
							reqjson.put("tokenId", tokenId);
							reqjson.put("timestamp", timestamp);
		
							callJson="method=logout"+"&"+"request="+reqjson.toString();
							log.debug("参数："+callJson);
		
							String reJson = Util.doHttpPostUseHead(url, callJson, "UTF-8", 10000, 0, headMap);
							log.debug("登出注销调用返回信息：" + reJson.toString());
		
							JSONObject loginoutObject = new JSONObject(reJson);
							String success = KHUtil.GetJV(loginoutObject, "success");
		
							//清空原有Token
							eliteBean.update("update SYSC_PARAMETER set PARAMETERVALUE = '' where PARAMETER_ID = 'SSOTOK'", "dataSource");
		
							return success;
						} catch (JSONException e) {
							log.error( "SSO 登出注销处理失败，" + e.getMessage());
						}
					}
				}
			}
		
			// SSO 下拉任务 pullTask
			public String getpullTask(EliteBean eliteBean,String tokenId){
		
				// 获取当前同步时间同步时间
				String timestamp = String.valueOf(System.currentTimeMillis());
				timestamp = timestamp.substring(0, 13);
				def url= getProperty.get("SSO.URL");
		
				// 设置头文件
				Map<String, String> headMap = new HashMap<String, String>();
				headMap.put("Content-Type", "application/x-www-form-urlencoded");
		
				try {
					JSONObject reqjson = new JSONObject();
					String callJson = "";
					reqjson.put("tokenId", tokenId);
					reqjson.put("timestamp", timestamp);
		
					callJson="method=pullTask"+"&"+"request="+reqjson.toString();
					log.debug("参数："+callJson);
		
					String reJson = Util.doHttpPostUseHead(url, callJson, "UTF-8", 10000, 0, headMap);
					log.debug("pullTask调用返回信息：" + reJson.toString());
					if(reJson == null || reJson.equals("null") || reJson.length() <= 0){
						return null;
					}
		
					JSONObject pullTaskObject = new JSONObject(reJson);
					String success = KHUtil.GetJV(pullTaskObject, "success");
					String effectOn = KHUtil.GetJV(pullTaskObject, "effectOn");
					log.debug("pullTask success："+success+"	,effectOn:"+effectOn);
		
					String data = KHUtil.GetJV(pullTaskObject, "data");
					log.debug("pullTask data："+data);
		
					JSONObject userdata = new JSONObject(data);
					String Loginname = KHUtil.GetJV(userdata, "username");
					String Staffname = KHUtil.GetJV(userdata, "fullname");
					String mobile = KHUtil.GetJV(userdata, "mobile");
					String disabled = KHUtil.GetJV(userdata, "isDisabled");
		
					if(success=='true'&&Loginname!='') {
						//检查是否是本地账号
						def localAdmin =eliteBean.chaxun_sql("Select Count(*) As Countnum From staff Where Loginname = '"+Loginname+"' ", "dataSource");
						def localcount = localAdmin.get(0).get("Countnum");
						log.debug("检查是否是本地账号:" + localcount);
		
						String[] data1=new String[1];
						int[] dataresult1;
						//新增(inserted),更新(updated),禁用(disabled),启用(enabled),删除(deleted)
						if(effectOn=='CREATED'&&localcount <= 0) {
							String staff_id = KHUtil.getRandomString(6).toUpperCase();
							data1[0] = "Insert Into staff (Staff_Id, Staffname, Workstatus, Createdby, Createddate, Modifiedby, Modifieddate, Loginname, Wrongpwdcount,Pwdmodify) Values ('"+staff_id+"', '"+Staffname+"', Case When '"+disabled+"' = 'false' Then 'ONLINE' Else 'QUIT' End, 'SW_SSO', GETDATE(), 'SW_SSO', GETDATE(), '"+Loginname+"', 0,getdate())";
							log.debug("当前登陆人员已经存在CC系统账号执行更新SQL:" + data1.toString());
							dataresult1 = eliteBean.updateBatch(data1, "dataSource");
							log.debug("CC系统登录信息表STAFF操作SQL结果:" + dataresult1.toString());
						}else if(effectOn=='UPDATED'){
							data1[0] = "Update staff Set Staffname = '" + Staffname + "', MOBILE = '" + mobile + "',Workstatus = Case When '" + disabled + "' = 'false' Then 'ONLINE' Else 'QUIT' End, Pwdmodify = getdate(), Wrongpwdcount = 0 Where Loginname = '" + Loginname + "'";
							log.debug("当前登陆人员已经存在CC系统账号执行更新SQL:" + data1.toString());
							dataresult1 = eliteBean.updateBatch(data1, "dataSource");
							log.debug("CC系统登录信息表STAFF操作SQL结果:" + dataresult1.toString());
						}else if(effectOn=='DISABLED'){
							data1[0] = "Update staff Set Staffname = '" + Staffname + "', MOBILE = '" + mobile + "',Workstatus = 'QUIT' , Pwdmodify = getdate(), Wrongpwdcount = 0 Where Loginname = '" + Loginname + "'";
							log.debug("当前登陆人员已经存在CC系统账号执行更新SQL:" + data1.toString());
							dataresult1 = eliteBean.updateBatch(data1, "dataSource");
							log.debug("CC系统登录信息表STAFF操作SQL结果:" + dataresult1.toString());
						}else if(effectOn=='ENABLED'){
							data1[0] = "Update staff Set Staffname = '" + Staffname + "', MOBILE = '" + mobile + "',Workstatus = 'ONLINE' , Pwdmodify = getdate(), Wrongpwdcount = 0 Where Loginname = '" + Loginname + "'";
							log.debug("当前登陆人员已经存在CC系统账号执行更新SQL:" + data1.toString());
							dataresult1 = eliteBean.updateBatch(data1, "dataSource");
							log.debug("CC系统登录信息表STAFF操作SQL结果:" + dataresult1.toString());
						}else if(effectOn=='DELETED'){
							data1[0] = "Update staff Set Staffname = '" + Staffname + "', MOBILE = '" + mobile + "',Workstatus = 'QUIT' , Pwdmodify = getdate(), Wrongpwdcount = 0 Where Loginname = '" + Loginname + "'";
							log.debug("当前登陆人员已经存在CC系统账号执行更新SQL:" + data1.toString());
							dataresult1 = eliteBean.updateBatch(data1, "dataSource");
							log.debug("CC系统登录信息表STAFF操作SQL结果:" + dataresult1.toString());
						}
							
					}
					return pullTaskObject;
				} catch (JSONException e) {
					log.error( "下拉任务 pullTask处理失败，" + e.getMessage());
				}
			}
			// SSO 下拉完成 pullFinish
			public String getpullFinish(EliteBean eliteBean,String tokenId,String taskId,String pullTasksuccess,String guid){
		
				// 获取当前同步时间同步时间
				String timestamp = String.valueOf(System.currentTimeMillis());
				timestamp = timestamp.substring(0, 13);
				def url= getProperty.get("SSO.URL");
		
				// 设置头文件
				Map<String, String> headMap = new HashMap<String, String>();
				headMap.put("Content-Type", "application/x-www-form-urlencoded");
		
				try {
					JSONObject reqjson = new JSONObject();
					String callJson = "";
					reqjson.put("tokenId", tokenId);
					reqjson.put("taskId", taskId);
					reqjson.put("success", pullTasksuccess);
					reqjson.put("guid", guid);
					reqjson.put("timestamp", timestamp);
		
					callJson="method=pullFinish"+"&"+"request="+reqjson.toString();
					log.debug("参数："+callJson);
		
					String reJson = Util.doHttpPostUseHead(url, callJson, "UTF-8", 10000, 0, headMap);
					//log.debug("pullFinish调用返回信息：" + reJson.toString());
		
					JSONObject pullFinishObject = new JSONObject(reJson);
					String success = KHUtil.GetJV(pullFinishObject, "success");
					log.debug("pullFinish success："+success);
					return success;
				} catch (JSONException e) {
					log.error( "下拉完成 pullFinish处理失败，" + e.getMessage());
				}
			
	}
}